"""
文件上传API蓝图
提供文件上传功能
"""

from flask import Blueprint, request, jsonify, current_app
import os
import logging
from app.tools.utils import get_safe_filename, validate_file_extension

# 创建文件上传API蓝图
file_upload_bp = Blueprint('file_upload', __name__, url_prefix='/upload')

def allowed_file(filename, allowed_extensions):
    """检查文件格式是否允许"""
    return validate_file_extension(filename, allowed_extensions)

@file_upload_bp.route('/audio', methods=['POST'])
def upload_audio():
    """上传音频文件"""
    try:
        if 'file' not in request.files:
            return jsonify({'error': '没有上传文件'}), 400
        
        file = request.files['file']
        if file.filename == '':
            return jsonify({'error': '没有选择文件'}), 400
        
        if not allowed_file(file.filename, current_app.config['ALLOWED_EXTENSIONS']):
            return jsonify({'error': '不支持的文件格式'}), 400
        
        # 获取可选的路径参数
        custom_path = request.form.get('path', None)
        
        # 构建上传路径
        if custom_path:
            # 如果提供了自定义路径，将其与UPLOAD_FOLDER拼接
            upload_folder = os.path.join(current_app.config['UPLOAD_FOLDER'], custom_path)
            # 确保目录存在
            os.makedirs(upload_folder, exist_ok=True)
            logging.info(f"使用自定义上传路径: {upload_folder}")
        else:
            # 使用默认的UPLOAD_FOLDER
            upload_folder = current_app.config['UPLOAD_FOLDER']
            logging.info(f"使用默认上传路径: {upload_folder}")
        
        # 生成安全的文件名
        original_filename = file.filename
        #safe_filename = get_safe_filename(original_filename)
        safe_filename = original_filename
        
        # 保存文件到指定路径
        upload_path = os.path.join(upload_folder, safe_filename)
        file.save(upload_path)
        
        # 检查文件是否成功保存
        if not os.path.exists(upload_path):
            return jsonify({'error': '文件保存失败'}), 500
        
        # 获取文件大小
        file_size = os.path.getsize(upload_path)
        
        return jsonify({
            'success': True,
            'filename': safe_filename,
            'original_filename': original_filename,
            'file_path': upload_path,
            'file_size': file_size,
            'upload_folder': upload_folder,
            'custom_path': custom_path,
            'message': '文件上传成功'
        })
    
    except Exception as e:
        logging.error(f"文件上传失败: {e}")
        return jsonify({'error': str(e)}), 500

@file_upload_bp.route('/audio/batch', methods=['POST'])
def upload_audio_batch():
    """批量上传音频文件"""
    try:
        if not request.files:
            return jsonify({'error': '没有上传文件'}), 400

        # 获取可选的路径参数
        custom_path = request.form.get('path', None)
        
        # 构建上传路径
        if custom_path:
            # 如果提供了自定义路径，将其与UPLOAD_FOLDER拼接
            upload_folder = os.path.join(current_app.config['UPLOAD_FOLDER'], custom_path)
            # 确保目录存在
            os.makedirs(upload_folder, exist_ok=True)
            logging.info(f"使用自定义上传路径: {upload_folder}")
        else:
            # 使用默认的UPLOAD_FOLDER
            upload_folder = current_app.config['UPLOAD_FOLDER']
            logging.info(f"使用默认上传路径: {upload_folder}")

        # 获取所有文件，包括同名文件
        files = []
        for key in request.files:
            file_list = request.files.getlist(key)
            files.extend(file_list)
        
        if not files or all(f.filename == '' for f in files):
            return jsonify({'error': '没有选择文件'}), 400
        
        uploaded_files = []
        
        for file in files:
            if file.filename == '':
                continue
            
            if not allowed_file(file.filename, current_app.config['ALLOWED_EXTENSIONS']):
                return jsonify({'error': f'不支持的文件格式: {file.filename}'}), 400
            
            # 生成安全的文件名
            original_filename = file.filename
            #safe_filename = get_safe_filename(original_filename)
            safe_filename = original_filename
            
            # 保存文件到指定路径
            upload_path = os.path.join(upload_folder, safe_filename)
            file.save(upload_path)
            
            # 检查文件是否成功保存
            if not os.path.exists(upload_path):
                return jsonify({'error': f'文件保存失败: {original_filename}'}), 500
            
            # 获取文件大小
            file_size = os.path.getsize(upload_path)
            
            uploaded_files.append({
                'filename': safe_filename,
                'original_filename': original_filename,
                'file_path': upload_path,
                'file_size': file_size,
                'upload_folder': upload_folder
            })
        
        return jsonify({
            'success': True,
            'uploaded_files': uploaded_files,
            'count': len(uploaded_files),
            'upload_folder': upload_folder,
            'custom_path': custom_path,
            'message': f'成功上传 {len(uploaded_files)} 个文件到 {upload_folder}'
        })
    
    except Exception as e:
        logging.error(f"批量文件上传失败: {e}")
        return jsonify({'error': str(e)}), 500
